package com.maven.front.controller.frontMyPersonal;

import com.maven.front.aop.MyLog;
import com.maven.front.bean.*;
import com.maven.front.dto.EduCourseDto;
import com.maven.front.dto.MyEduQuesstionDto;
import com.maven.front.mapper.EduCourseStudyhistoryMapper;
import com.maven.front.service.myPersonal.MyPersonalService;
import com.maven.front.util.BeanUtils;
import com.maven.front.util.FileUploadService;
import com.maven.front.util.MD5;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @program: web-front
 * @description: 前台个人资料修改
 * @author: WangYiLong
 * @create: 2020-08-08 15:19
 **/
@Slf4j
@RestController
@RequestMapping("user")
public class MyPersonalController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Resource
    private MyPersonalService myPersonalService;

    @Resource
    private FileUploadService fileUploadService;

    @Resource
    private EduCourseStudyhistoryMapper courseStudyhistoryMapper;



    /**
     *  修改前台个人资料
     * @param eduUser
     * @return
     */
    @MyLog(value = "修改前台个人资料")
    @PostMapping("/update/personal")
    public Result update(  EduUser eduUser, @RequestHeader String token){
        log.info("******:"+eduUser.toString());
        int num = myPersonalService.update(eduUser);
        if(num<=0){
            return new Result(40004,"修改失败");
        }
        EduUser newUser = myPersonalService.getById(eduUser.getUserId());
        redisTemplate.opsForValue().set(token,newUser);
        redisTemplate.expire(token,15, TimeUnit.MINUTES);
        return new Result(200,"成功");
    }

    /**
     * 修改个人头像
     * @param file
     * @param token
     * @return
     */
    @MyLog(value = "修改用户个人头像")
    @PostMapping("update/img")
    public Result updateImg(MultipartFile file, @RequestHeader String token){
        log.info("****file:"+file);
        FileUploadResult fileUploadResult = fileUploadService.upload(file);
        if(fileUploadResult.getResponse().equals("success")){
            log.info(fileUploadResult.toString());
            EduUser eduUser = (EduUser) redisTemplate.opsForValue().get(token);
            eduUser.setPicImg(fileUploadResult.getName());
            myPersonalService.update(eduUser);
            EduUser newUser = myPersonalService.getById(eduUser.getUserId());
            redisTemplate.opsForValue().set(token,newUser);
            redisTemplate.expire(token,15, TimeUnit.MINUTES);
            return new Result(200,"成功");
        }else{
            return new Result(505,"上传失败");
        }
    }

    /**
     *  修改用户密码
     * @param nowPassword
     * @param newPassword
     * @param token
     * @return
     */
    @MyLog(value = "修改前台用户密码")
    @PostMapping("update/password")
    public Result updatePassword(String nowPassword,String newPassword,@RequestHeader String token){
        EduUser eduUser = (EduUser) redisTemplate.opsForValue().get(token);
        String sign = MD5.sign(nowPassword,eduUser.getEmail(),"utf-8");
        log.info("******nowPass:"+nowPassword+"********sign:"+sign);
        if(!eduUser.getPassword().equals(sign)){
            return new Result(506,"原密码不正确");
        }
        eduUser.setPassword(MD5.sign(newPassword,eduUser.getEmail(),"utf-8"));
        myPersonalService.update(eduUser);
        EduUser newUser = myPersonalService.getById(eduUser.getUserId());
        redisTemplate.opsForValue().set(token,newUser);
        redisTemplate.expire(token,15, TimeUnit.MINUTES);
        return new Result(200,"修改成功");
    }

    @MyLog(value = "前台个人中心已观看课程查询")
    @GetMapping("viewCourse")
    public Result getViewCourse(Integer userId){
        List<EduCourse> list = myPersonalService.select(null);
        if(CollectionUtils.isEmpty(list)){
            return new Result(509,"查询失败");
        }
        List<EduCourseDto> courseDtos = getPercentage(list,userId,1);
        return new Result(200,"成功",courseDtos);
    }

    @MyLog(value = "前台免费课程")
    @GetMapping("freeCourse")
    public Result getFreeCourse(Integer userId){
        List<EduCourse> list = myPersonalService.getFreeCourse();
        if(CollectionUtils.isEmpty(list)){
            return new Result(303,"查询无数据");
        }
        List<EduCourseDto> courseDtos = getPercentage(list,userId,2);

        return new Result(200,"成功",courseDtos);
    }

    //获取课程观看进度
    public List<EduCourseDto> getPercentage(List<EduCourse> list,Integer userId,int type){
        List<EduCourseDto> courseDtos = new ArrayList<>();
        List<EduCourseKpoint> kpoints = myPersonalService.selectTotalTime();
        List<EduCourseStudyhistory> histories = myPersonalService.selectViewTimeByUserId(userId);
        for(EduCourse course:list){
            EduCourseDto dto = new EduCourseDto();
            BeanUtils.copy(course,dto);
            for(EduCourseKpoint k:kpoints){
                if(course.getCourseId()==k.getCourseId()){
                    for(EduCourseStudyhistory h:histories){
                        if(k.getCourseId()==h.getCourseId()){
                            log.info("***********"+h.getSumTime()+"************"+k.getTotalTime());
                            int percentage = (int) Math.floor((h.getSumTime()*1.0/k.getTotalTime())*100);
                            dto.setPercentage(percentage);
                            if(type==1){
                                courseDtos.add(dto);
                            }

                        }
                    }
                }
            }
            if(type==2){
                courseDtos.add(dto);
            }
        }
        log.info("************"+courseDtos.size());
        return courseDtos;
    }

    @MyLog(value = "个人中心提问")
    @GetMapping("personal/question")
    public Result getQuestion(Integer cusId){
        //个人所有提问
        List<EduQuestions> questions = myPersonalService.selectByCusId(cusId);
//        log.info("*************"+questions.toString());
        //针对提问的所有回答
        List<EduQuestionsComment> questionsComments = myPersonalService.getQuesstionsComment(cusId);
        compare(questionsComments);
        List<MyEduQuesstionDto> list = setComment(questions,questionsComments);
        Collections.sort(list, new Comparator<MyEduQuesstionDto>() {
            @Override
            public int compare(MyEduQuesstionDto o1, MyEduQuesstionDto o2) {
                return o2.getAddTime().compareTo(o1.getAddTime());
            }
        });
        log.info("**********"+list.size());
        return new Result(200,"成功",list);
    }

    @MyLog(value = "个人中心我的回帖")
    @GetMapping("personal/comment")
    public Result getQuesstionsCommont(Integer cusId){
        List<EduQuestionsComment> comments = myPersonalService.getQuesstionsComment(cusId);

        List<EduQuestions> questions = myPersonalService.selectByPrimaryKeys(comments);
        log.info("*************"+questions.size());
        List<EduUser> users = myPersonalService.selectByUserIds(questions);
        compare(comments);
        List<MyEduQuesstionDto> list = setComment(questions,comments);
        for(MyEduQuesstionDto d:list){
            for(EduUser u:users){
                if(u.getUserId()==d.getCusId()){
                    d.setEduUser(u);
                }
            }
        }
//        log.info("************"+list.size());
        return new Result(200,"成功",list);
    }

    //排序
    public void compare(List<EduQuestionsComment> list){
        Collections.sort(list, new Comparator<EduQuestionsComment>() {
            @Override
            public int compare(EduQuestionsComment o1, EduQuestionsComment o2) {
                return o2.getAddTime().compareTo(o1.getAddTime());
            }
        });
    }

    //将最新回答赋值给对应问题的对象中
    public List<MyEduQuesstionDto> setComment(List<EduQuestions> questions,List<EduQuestionsComment> comments){
        List<MyEduQuesstionDto> dtos = new ArrayList<>();
        for(EduQuestions q:questions){
            MyEduQuesstionDto dto = new MyEduQuesstionDto();
            BeanUtils.copy(q,dto);
            for(EduQuestionsComment c:comments){
                if(q.getId()==c.getQuestionId()){
                    dto.setEduQuestionsComment(c);
                    break;
                }
            }
            dtos.add(dto);
        }
        return dtos;
    }

}
